//
//  PKRequestManager.m
//  PianKe
//
//  Created by Li on 15/7/21.
//  Copyright (c) 2015年 Li. All rights reserved.
//

#import "LJRequestManagerBlock.h"

#import <UIKit/UIKit.h>

#import "CRToast.h"

@interface LJRequestManagerBlock ()<NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSMutableData *data;

@end

@implementation LJRequestManagerBlock

+ (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr dic:(NSDictionary *)dic finish:(RequestFinish)finish error:(RequestError)error{
    LJRequestManagerBlock *manager = [[LJRequestManagerBlock alloc] init];
    [manager manager:requestType requestWith:urlStr dic:dic finish:finish error:error];
}

- (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr dic:(NSDictionary *)dic finish:(RequestFinish)finish error:(RequestError)error{
    self.requestFinish = finish;
    self.requestError = error;
    
    
    if (requestType == GET) {
        
        NSString *url = [NSString stringWithFormat:@"%@%@",urlStr,[self dicToParameter:dic]];
        urlStr = url;
//       NSLog(@"%@",urlStr);

    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    _data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.requestFinish(_data);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self test];
    self.requestError(error);
}

- (NSString *)dicToParameter:(NSDictionary *)dic{

    NSMutableString *str = [[NSMutableString alloc] initWithCapacity:0];
    for (NSString *key in [dic allKeys]) {
        [str appendString:[NSString stringWithFormat:@"&%@=%@",key,dic[key]]];
    }
    return str;
}

- (void)test{
    
    NSDictionary *options = @{
                              kCRToastTextKey : @"请检查网络连接!",
                              kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                              kCRToastBackgroundColorKey : [UIColor lightGrayColor],
                              kCRToastAnimationInTypeKey : @(CRToastAnimationTypeSpring),
                              kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeSpring),
                              kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionTop),
                              kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionBottom)
                              };
    [CRToastManager showNotificationWithOptions:options
                                completionBlock:^{

                                }];
}


@end
